<template>
    <!-- 自扣还款查询/修改/取消 -->
    <div class="autoRepayAcctSetting" v-loading="isLoading">
        <cardComponent pageTitle="自扣还款查询/修改/取消">
            <template slot="cardBody">
                <div class="dialogVisible">
                    <el-form
                        ref="searchFormOne"
                        :model="searchFormOne"
                        :inline="true"
                        label-position="right"
                        size="small"
                        label-width="150px"
                        :rules="rules"
                    >
                        <el-row>
                            <el-col :span="11" :offset="1">
                                <el-form-item label="账户类别:" class="text_fl">
                                    <el-select
                                        v-model="searchFormOne.accttype"
                                        placeholder="请选择账户类别"
                                        clearable
                                        @change="changeAccttype"
                                    >
                                        <el-option
                                            v-for="item in AccountionTYPE_INFO"
                                            :label="item.label"
                                            :value="item.code"
                                            :key="item.label"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="11">
                                <el-form-item label="卡号:" class="text_fl">
                                    <el-select
                                        v-model="searchFormOne.cardno"
                                        placeholder="请选择卡号"
                                        disabled
                                    >
                                        <el-option
                                            v-for="item in cardList"
                                            :label="item.CARDNBR"
                                            :value="item.CARDNBR"
                                            :key="item.CARDNBR"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="11" :offset="1">
                                <el-form-item label="自扣账号:" label-position="left" prop="ACCT">
                                    <el-input v-model="searchFormOne.ACCT" @blur="checkagain"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="11">
                                <el-form-item
                                    class="form_item"
                                    label-position="left"
                                    prop
                                    label="还款方式:"
                                >
                                    <el-radio-group v-model="searchFormOne.REPAYCODE" width="250px">
                                        <el-radio label="M">最低还款额</el-radio>
                                        <el-radio label="T">全额还款</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="11" :offset="1">
                                <el-form-item label="到期还款日:" label-position="left" prop="DUEDATE">
                                    <el-input v-model="searchFormOne.DUEDATE" disabled></el-input>
                                    <!-- <span style="color:red;">{{ searchFormOne.DUEDATE |validat }}</span> -->
                                </el-form-item>
                            </el-col>
                            <el-col :span="11">
                                <el-form-item label="还款账号关系状态:" label-position="left">
                                    <el-input :value="searchFormOne.STATUS | getText" disabled></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <div v-show="isShowView2" align="center" style="margin-top:50px;">
                            <el-table
                                :data="trsData"
                                border
                                stripe
                                class="heard-bg"
                                style="width: 80%;"
                                size="small"
                            >
                                <el-table-column label="交易结果">
                                    <el-table-column prop="CARDNO" label="操作卡号"></el-table-column>

                                    <el-table-column prop="OPTION" label="操作类型"></el-table-column>

                                    <el-table-column prop="RESULT" label="结果描述"></el-table-column>
                                </el-table-column>
                            </el-table>
                        </div>
                        <!-- 话术 -->
                        <div class="hstable_wrap" v-if="speechList.length!=0">
                            <el-table
                                :data="speechList"
                                border
                                stripe
                                header-row-class-name="headerRow"
                                ref="showListTable"
                                class="heard-bg business_table hstable"
                                @selection-change="handleSelectionChange"
                            >
                                <el-table-column type="selection" label=" " min-width="55"></el-table-column>
                                <el-table-column label="业务话术">
                                    <template slot-scope="scope">{{scope.row.content}}</template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-form>
                    <div class="btnBox">
                        <el-button type="primary" size="small" @click="checkAcct">借记卡校验</el-button>
                        <el-button
                            type="primary"
                            size="small"
                            @click="hanleUpdate"
                            :disabled="(!ifcheckacct)||checkflag"
                        >申请自扣</el-button>
                        <el-button type="primary" size="small" @click="hanleCancel">取消自扣</el-button>
                        <el-button
                            type="primary"
                            size="small"
                            @click="updatehistory"
                            v-show="isShowView"
                        >修改记录查询</el-button>
                    </div>
                </div>
            </template>
        </cardComponent>
    </div>
</template>

<script>
import { mapState } from 'vuex';
import moment from 'moment';
import { getAccountTypeName, getBusinessMenuId } from '@/utils/Common';
import { RegConfig } from '@/utils/RegConfig';
import cardComponent from '@/components/cardComponent/cardComponent.vue';

export default {
    name: 'autoRepayAcctSetting',
    components: {
        cardComponent,
    },
    data() {
        // const validateDueDate = (rule, value, callback) => {
        //     const resDate = moment().format('YYYYMMDD') //20211022
        //     console.log('resDate__________', resDate);//20211020
        //     if (value != '') {
        //         let days = parseInt(value) - parseInt(resDate);
        //         if (Math.abs(days) <= 3) {
        //             callback(new Error('距离最后还款日不足3天'));
        //         }
        //     }
        //     callback();
        // };
        return {
            searchFormOne: {
                ACCT: '',//储蓄卡号
                REPAYCODE: '', // 自动还款方式
                STATUS: '', // 还款关系00：委托关系成功 AA：关系待验证 其他：失败
                DUEDATE: '',//到期还款日
                accttype: '',//账户类别
                cardno: '',//信用卡号
                TRANSTATUS: '',//交易结果
            },
            FLAG: '1', // 查询修改标志 1：查询；2：修改；3：新增；4：删除；
            accountType: '', //账户类型
            accountNo: '', //账号
            isLoading: false,
            rules: {
                ACCT: [
                    { required: true, message: '请填写自扣账号', trigger: 'blur' },
                    { pattern: RegConfig.cardNo, message: '银行卡号应由13-21位数字组成', trigger: 'blur' },

                ],
                // DUEDATE: [
                //     { validator: validateDueDate, trigger: 'change' }
                // ]

            },
            oldAcct: '',//原自扣绑定账号
            cardList: [],//当前卡列表
            isShowView: false,//是否显示修改历史查询按钮
            isShowView2: false,//是否显示交易结果
            ifcheckacct: false,//是否已校验储蓄卡
            checkflag: false,//储蓄卡校验结果是否拦截
            trsData: [],//交易结果列表
            speechList: [],//话术列表
            selectedList: [],
            MenuId: '',
            outCard: '',
        };
    },
    filters: {
        getText(val) {
            if (val === '00') {
                return '委托关系成功';
            } if (val === 'AA') {
                return '委托关系待验证';
            }
            return '';
        },

    },
    async mounted() {
        this.MenuId = this.$route.params.id || '';
        // this.searchFormOne.CARDNO = this.cardInfo_3004.CARDNO
        //this.accountType = await getAccountTypeName(this.cardList_3601, this.cardInfo_3004, this);
        // this.accountNo = this.cardInfo_3004.CARDNO;
        this.init();
        await this.getspeechList();

    },
    computed: mapState({
        cardInfo_3004: state => state.common.cardInfo_3004,
        cardList_3601: state => state.common.cardList_3601,
        defaultParams: state => state.common.defaultParams,
        defaultpinFlag: state => state.common.pinFlag,
        AccountionTYPE_INFO: state => state.common.AccountionTYPE_INFO, //账户类别列表
        cardAccountInfo_3001: state => state.common.cardAccountInfo_3001,
        isCurrentMenuInfo: state => state.menu.isCurrentMenuInfo,
        businessMenu: state => state.menu.businessMenu,
    }),
    methods: {
        init() {
            console.log("默认账户类别：" + this.cardInfo_3004.CATEGORY);
            console.log("默认账户：" + this.cardInfo_3004.CARDNO);
            this.searchFormOne.accttype = this.cardInfo_3004.CATEGORY + '';
            this.searchFormOne.cardno = this.cardInfo_3004.CARDNO;
            this.cardList = [];
            this.cardList_3601.forEach((item) => {
                if (item.CATEGORY + '' === this.cardInfo_3004.CATEGORY + '') {
                    this.cardList.push(item);
                }
            });
            console.log("cardList", this.cardList);
            this.getOrSendSettingInfo('1');

            this.searchFormOne.DUEDATE = this.cardAccountInfo_3001.DUEDATE;//到期还款日

        },
        changeAccttype(val) {
            console.log("当前账户类型：" + val);
            let hasDefault = false; //是否包含默认卡
            this.cardList = [];
            this.cardList_3601.forEach((item) => {
                if (item.CATEGORY + '' === val) {
                    this.cardList.push(item);
                    if (item.CARDNBR === this.cardInfo_3004.CARDNO) {
                        hasDefault = true;
                    }
                }
            });

            //包含默认卡，卡号显示默认卡，不包含，显示cardList里第一张卡号
            if (hasDefault) {
                this.searchFormOne.cardno = this.cardInfo_3004.CARDNO;
            } else {
                this.searchFormOne.cardno = this.cardList[0].CARDNBR;
            }
            //切换账户，重新查询自扣还款账号
            this.getOrSendSettingInfo('1');

            //切换账号，重新查询到期还款日
            this.getDueday();

        },
        //根据菜单id查询话术列表
        async getspeechList() {
            console.log("this.isCurrentMenuInfo.id", this.isCurrentMenuInfo.id);
            var checkParam = {
                'id': this.MenuId || this.isCurrentMenuInfo.id,
            };
            this.$post.busiMenu.getlistByMenuId(checkParam).then((res) => {
                console.log("话术查询结果：", res);
                if (res.status === 200) { // http通讯成功
                    if (res.data.status == 0) { // 业务请求成功
                        this.speechList = res.data.content;
                    }
                }
            });
        },
        handleSelectionChange(val) {
            this.selectedList = val;
        },
        /**
        * 调核心接口1301查询储蓄卡账户信息
        */
        checkAcct() {
            this.$refs.searchFormOne.validate((valid) => { //提交前，表单校验
                if (valid) {
                    const resDate = moment().format('YYYYMMDD'); //20211022
                    const value = this.searchFormOne.DUEDATE;//20211025
                    let days = parseInt(value) - parseInt(resDate);
                    // 前三天 
                    if (days > 0 && days <= 3) {
                        this.$alert('距离最后还款日不足3天', '自扣还款提示', {
                            customClass: 'warning', type: 'warning',
                        })
                    }
                    if (this.searchFormOne.ACCT.trim() === '') {
                        this.$alert('请输入储蓄卡号', '提示', {
                            customClass: 'error', type: 'error',
                        });
                        return;
                    }
                    const appBody = {
                        CrdNo: this.searchFormOne.ACCT, // 储蓄卡号
                        ActNo: '', // 账号
                        VerfPwdFlg: '0', //是否校验密码
                        Pin: '',//密码

                    };
                    const params = JSON.parse(JSON.stringify(this.defaultParams));
                    params.body.appHead.tranCode = '1301';
                    params.body.appBody = appBody;

                    // 跑 3072 交易
                    this.$post.common.esbtran(params).then((res) => {
                        if (res.status === 200) { // 接口请求成功
                            this.ifcheckacct = true;//已做过借记卡校验
                            const result = JSON.parse(res.data.jsonRes);
                            console.log(result, 'result -- 1301');
                            if (result.sysHead.rspCd === '000000') {
                                console.log("借记卡信息：", result.body.appBody);
                                console.log(result.body.appBody.IdentNo + "借记卡信息：" + this.cardInfo_3004.CUSTID);
                                //是否本人名下
                                if (result.body.appBody.IdentNo + '' != this.cardInfo_3004.CUSTID + '') {
                                    this.$alert('储蓄卡非本人名下，不能办理此业务', '提示', {
                                        customClass: 'error', type: 'error',

                                    });
                                    this.checkflag = true;
                                    return;
                                }
                                //是否是一类户
                                if (result.body.appBody.ThrClCrdActFlg + '' === '3') {
                                    this.$alert('储蓄卡为三类户，不能办理此业务', '提示', {
                                        customClass: 'error', type: 'error',
                                    });
                                    this.checkflag = true;
                                    return;
                                }

                                //状态是否正常
                                if ((result.body.appBody.AcctStsCd + '').indexOf('1') > 0) {
                                    this.$alert('请注意与客户确认借记卡状态', '提示', {
                                        customClass: 'error', type: 'error',
                                    });
                                    this.checkflag = true;
                                    // return;
                                }
                                // if (result.body.appBody.ThrClCrdActFlg + '' === '2') {
                                //     console.log("二类户：", result.body.appBody.ThrClCrdActFlg);
                                //     this.$alert('储蓄卡为二类户，校验成功', '提示', {
                                //         customClass: 'success', type: 'success',
                                //     });
                                // } else {
                                //     this.$alert('储蓄卡校验成功', '提示', {
                                //         customClass: 'success', type: 'success',
                                //     });
                                // }
                                this.outCard = this.searchFormOne.ACCT.trim();
                                this.checkflag = false;

                            } else {
                                const errorMsg = `错误代码：${result.sysHead.rspCd}, 错误信息：${result.sysHead.rspDesc}`;
                                this.$alert(errorMsg, result.sysHead.rspDesc, {
                                    customClass: 'error', type: 'error',
                                });
                                this.checkflag = true;
                                return;
                            }
                        } else {
                            this.$message.error('请求失败');
                            this.checkflag = true;
                        }
                    });
                }
            })
        },
        //验证成功之后改变借记卡号，申请按钮不可用，需重新验证借记卡号
        checkagain() {
            if (this.outCard === '') {
                return;
            }

            if (this.outCard !== '' && this.outCard !== this.searchFormOne.ACCT.trim()) {
                this.checkflag = true;
            } else {
                this.checkflag = false;
            }
        },
        // 点击按钮修改
        hanleUpdate() {
            this.$refs.searchFormOne.validate((valid) => { //提交前，表单校验
                if (valid) {

                    if (this.searchFormOne.REPAYCODE === '') {
                        this.$alert('请选择自扣还款方式！', '提示', {
                            customClass: 'warning', type: 'warning',
                        });
                        return false;
                    }

                    console.log("this.selectedList.length", this.selectedList.length);
                    if (this.selectedList.length != this.speechList.length) {
                        this.$alert('话术尚未全部勾选！', '提示', {
                            customClass: 'warning', type: 'warning',
                        });
                        return;
                    }
                    this.$confirm('确定提交吗？', '提示', { customClass: 'warning', type: 'warning' }).then(() => {
                        this.FLAG = '2';
                        // 此处不固定设置flag，查询成功即修改，查询失败即新增
                        this.getOrSendSettingInfo('2');
                    }).catch(() => {
                    });
                }
            });
        },
        // 点击按钮取消
        hanleCancel() {
            console.log("this.selectedList.length", this.selectedList.length);
            if (this.selectedList.length != this.speechList.length) {
                this.$alert('话术尚未全部勾选！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                return;
            }
            this.$confirm('确定取消吗？', '提示', { customClass: 'warning', type: 'warning' }).then(() => {
                this.FLAG = '4';
                this.getOrSendSettingInfo('4');
            }).catch(() => {
            });
        },
        // 查询4017接口
        getOrSendSettingInfo(val) {
            console.log("val:", val);
            console.log("oldAcct:", this.oldAcct);
            if (val === '2' && this.oldAcct === '') {//如果点击修改，并且原自扣账号为空，修改标志改为3-新增
                this.FLAG = '3';
            } else {
                this.FLAG = val;
            }
            this.isLoading = true;
            const appBody = {
                CARDNBR: this.searchFormOne.cardno || '', // 卡号
                PINFLAG: '0', // 是否检查密码标志
                PIN: '', // 密码
                FLAG: this.FLAG, // 查询修改标志 1：查询；2：修改；3：新增；4：删除；
                ACCT: this.searchFormOne.ACCT, // 还款账号 查询修改标志为2、3、4时，必填
                REPAYCODE: this.searchFormOne.REPAYCODE, // 还款方式 T＝全额 M＝最小还款额查询修改标志为2、3、4时，必填
                CHECKFLG: '000000000000000', // 0、1串。系统根据银行的选择来对检查项目的检查。默认值为0为不检查，1为检查。其中：第一位：证件号码（银行上送证件类型时，对证件类型的验证是跟随证件号码验证同时处理；不上送证件类型时，不强制检验）第二位：姓名第三位：证件类型第四位：客户参考资料编号
                FORCEFLAG: '0', // 还款账号强制生效标志 1－还款账号强制立即生效；0-或者其他不强制生效，系统默认情况；必传
                IDTYPE: '', // 证件类型
                IDNO: '', // 证件号码
                ONUSFLAG: '', // 本行跨行标记
                RESERV: '', // 保留字段
                DEMOINFO: '', // 备注信息
                NAME: '', // 姓名
                CURRNUM: '156', //156：人民币

            };
            const defaultParams = JSON.parse(JSON.stringify(this.defaultParams));
            defaultParams.body.appHead.tranCode = '4017';
            defaultParams.body.appBody = appBody;
            // 4017交易
            this.$post.common.transPort(defaultParams).then((res) => {
                this.isLoading = false;

                if (res.status === 200) {
                    const result = JSON.parse(res.data.jsonRes);
                    console.log(result, "1111111111111111111111111111");
                    if (result.sysHead.rspCd === '000000') {
                        if (this.FLAG === '1') {//查询
                            console.log(result.body.appBody, 'result.body.appBody');
                            this.oldAcct = result.body.appBody.ACCT;
                            this.searchFormOne.ACCT = result.body.appBody.ACCT.trim();
                            this.searchFormOne.REPAYCODE = result.body.appBody.REPAYCODE;
                            this.searchFormOne.STATUS = result.body.appBody.STATUS;
                            //this.FLAG = '2'; //查询成功，即要修改 
                        } else if (this.FLAG === '2') {//修改；
                            this.$store.commit('common/UPDATE_AUTOREPAY_ACCT', result.body.appBody);
                            this.isShowView = true;
                            this.isShowView2 = true;
                            this.checkflag = true;
                            this.getOrSendSettingInfo('1');
                            this.trsData = [{
                                CARDNO: this.searchFormOne.cardno,
                                OPTION: '修改',
                                RESULT: '交易成功'
                            }];
                        } else if (this.FLAG === '3') {//新增；
                            this.$store.commit('common/UPDATE_AUTOREPAY_ACCT', result.body.appBody);
                            this.checkflag = true;
                            this.isShowView = true;
                            this.isShowView2 = true;
                            this.searchFormOne.TRANSTATUS = '交易成功';
                            this.trsData = [{
                                CARDNO: this.searchFormOne.cardno,
                                OPTION: '新增',
                                RESULT: '交易成功'
                            }];
                            this.getOrSendSettingInfo('1');
                        } else if (this.FLAG === '4') {//删除
                            this.$store.commit('common/UPDATE_AUTOREPAY_ACCT', "");
                            this.checkflag = true;
                            this.isShowView = true;
                            this.isShowView2 = true;
                            this.searchFormOne.TRANSTATUS = '交易成功';
                            this.trsData = [{
                                CARDNO: this.searchFormOne.cardno,
                                OPTION: '取消绑定',
                                RESULT: '交易成功'
                            }];
                            this.getOrSendSettingInfo('1');
                        }
                    } else {
                        if (this.FLAG === '1') {//查询
                            if (result.sysHead.rspCd === '009068') {
                                this.oldAcct = '';
                                this.searchFormOne.ACCT = '';
                                this.searchFormOne.REPAYCODE = '';
                                this.searchFormOne.STATUS = '';
                            }
                        } else if (this.FLAG === '2') {//修改；
                            this.isShowView2 = true;
                            this.trsData = [{
                                CARDNO: this.searchFormOne.cardno,
                                OPTION: '修改',
                                RESULT: '交易失败' + result.sysHead.rspMsg
                            }];
                        } else if (this.FLAG === '3') {//新增；
                            this.isShowView2 = true;
                            this.trsData = [{
                                CARDNO: this.searchFormOne.cardno,
                                OPTION: '新增',
                                RESULT: '交易失败' + result.sysHead.rspMsg
                            }];
                        } else if (this.FLAG === '4') {//删除
                            this.isShowView2 = true;
                            this.trsData = [{
                                CARDNO: this.searchFormOne.cardno,
                                OPTION: '取消绑定',
                                RESULT: '交易失败' + result.sysHead.rspMsg
                            }];
                        }
                    }
                } else {
                    this.$alert(
                        '请求失败！',
                        '提示',
                        {
                            customClass: 'error', type: 'error',
                        },
                    );
                }
            });
        },

        getDueday() {
            const appBody = {
                CARDNO: this.searchFormOne.cardno, // 卡号
                PINFLAG: '0', // 是否检查密码标志 0-不检查
            };
            const params = JSON.parse(JSON.stringify(this.defaultParams));
            params.body.appHead.tranCode = '3001';
            params.body.appBody = appBody;
            // 跑 3001 交易
            this.$post.common.transPort(params).then((res) => {
                if (res.status === 200) {
                    const result = JSON.parse(res.data.jsonRes);
                    if (result.sysHead.rspCd === '000000') {
                        console.log("this.searchFormOne.duedate", result.body.appBody.DUEDATE);
                        this.searchFormOne.DUEDATE = result.body.appBody.DUEDATE;

                    } else {
                        //this.$message.error(result.sysHead.rspMsg);
                    }
                } else {
                    //this.$message.error('请求失败');
                }

            });
        },

        updatehistory() {
            this.MenuId = getBusinessMenuId('/businessSystem/accountCardDetaileQuery', this.businessMenu);
            console.log('this.MenuId____', this.MenuId);
            this.$router.push({ name: 'accountCardDetaileQuery', path: '/businessSystem/accountCardDetaileQuery', params: { id: this.MenuId } });
        },

    },
};
</script>

<style lang='scss'>
.autoRepayAcctSetting {
    width: 98%;
    background: #fff;
    // padding:10px;
    box-sizing: border-box;
    border-radius: 5px;
    .el-input--small {
        font-size: 13px;
        .el-input {
            position: relative;
            font-size: 14px;
            display: inline-block;
            width: 30%;
        }
    }

    .form_item {
        width: 400px;
    }

    /* //头部内容 */
    .tab-header {
        width: 100%;
        text-align: left;
        span {
            font-size: 14px;
        }
        .headerTitle {
            font-size: 16px;
            margin: 10px 0px;
            color: skyblue;
        }
    }
    .dialogVisible {
        margin: 10px auto 0;
        form.el-form {
            text-align: center;
        }
        .el-form-item__content {
            text-align: left;
            .el-radio-group {
                display: inline-block;
                line-height: 1;
                vertical-align: text-bottom;
                width: 250px;
                .el-radio {
                    margin-top: 10px;
                    margin-right: 10px;
                }
            }
        }
        .el-form-item__error {
            width: 200px;
            color: #f56c6c;
            font-size: 12px;
            line-height: 1;
            padding-top: 4px;
            position: absolute;
            top: 100%;
            left: 0;
        }
    }
    .btnBox {
        margin-top: 40px;
        text-align: center;
    }
}
</style>
